/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 *

 * <p>
 * 版权所有，侵权必究！
 */

package io.api.modules.login.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import io.admin.common.exception.ErrorCode;
import io.admin.common.exception.RenException;
import io.admin.common.service.impl.BaseServiceImpl;
import io.admin.common.utils.ConvertUtils;
import io.api.modules.login.dao.UserDao;
import io.api.modules.login.dto.CaptchaLoginDTO;
import io.api.modules.login.dto.LoginDTO;
import io.api.modules.login.dto.PasswordDTO;
import io.api.modules.login.dto.UserDTO;
import io.api.modules.login.entity.TokenEntity;
import io.api.modules.login.entity.UserEntity;
import io.api.modules.login.entity.UserEquipmentEntity;
import io.api.modules.login.service.CaptchaService;
import io.api.modules.login.service.TokenService;
import io.api.modules.login.service.UserEquipmentService;
import io.api.modules.login.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@AllArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserDao, UserEntity> implements UserService {
    private final TokenService tokenService;
    private final CaptchaService captchaService;

    private final UserEquipmentService userEquipmentService;

    @Override
    public UserEntity getByMobile(String mobile) {
        UserEntity user = baseDao.getUserByMobile(mobile);
        if (Objects.isNull(user)) {
            throw new RenException(ErrorCode.ACCOUNT_NOT_EXIST);
        }
        // 用户未启用
        if (user.getUserstate() != 1) {
            throw new RenException(ErrorCode.ACCOUNT_DISABLE);
        }
        return user;
    }

    @Override
    public UserEntity getUserByUserId(Long userId) {
        return baseDao.getUserByUserId(userId);
    }

    @Override
    public Map<String, Object> login(LoginDTO dto) {
        UserEntity user = getByMobile(dto.getMobile());
        //密码错误
        if (!user.getPassword().equals(DigestUtil.sha256Hex(dto.getPassword()))) {
            throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
        }
        return login(dto.getBumber(), user);
    }

    @Override
    public Map<String, Object> captchaLogin(CaptchaLoginDTO dto) {
        UserEntity user = getByMobile(dto.getMobile());
        //密码错误
        if (!captchaService.validate(dto.getMobile(), dto.getCaptcha())) {
            throw new RenException(ErrorCode.CAPTCHA_ERROR);
        }
        return login(dto.getBumber(), user);
    }

    @Override
    public int resetPassword(PasswordDTO dto) {
        UserEntity user = getByMobile(dto.getMobile());
        if (!captchaService.validate(dto.getMobile(), dto.getCaptcha())) {
            throw new RenException(ErrorCode.CAPTCHA_ERROR);
        }
        if (!dto.getNewPassword().equals(dto.getRePassword())) {
            throw new RenException("两次密码输入不一致");
        }
        user.setPassword(DigestUtil.sha256Hex(dto.getNewPassword()));
        return baseDao.updateById(user);
    }

    @Override
    public List<UserDTO> selectByProjectId(Long projectId) {
        List<UserEntity> sourceList = baseDao.selectByProjectId(projectId);
        return ConvertUtils.sourceToTarget(sourceList, UserDTO.class);
    }

    private Map<String, Object> login(String bumber, UserEntity user) {
        UserEquipmentEntity userEquipmentEntity = userEquipmentService.check(user, bumber);

        //查看设备是否授权
        if (userEquipmentEntity.getState() != 1) {
            throw new RenException(ErrorCode.DEVICE_UNAUTHORIZED);
        }

        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getId());

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());

        return map;
    }

}